package com.wxxymaker.model.dao;

import com.blade.ioc.annotation.Bean;
import com.wxxymaker.model.entity.Email;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.core.AnimaQuery;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;

import java.util.Date;

/**
 * @Author: Soft
 * @Date: 2018/7/14 13:46
 * @Desc: 邮件dao层
 */
@Bean
public class EmailDao implements BaseDao<Email> {

    public Email add(Email email) {
        if (email != null) {
            email.setTime(new Date());
            Integer asInt = email.save().asInt();
            email.setId(asInt);
        }
        return email;
    }

    public Email delete(int id) {
        if (id > 0) {
            Email email = Anima.select().from(Email.class).byId(id);
            if (email != null) {
                email.delete();
                return email;
            }
        }
        return null;
    }

    public int change(Email email) {
        if (email != null) {
            return email.updateById(email.getId());
        }
        return -1;
    }

    public Email findOne(int id) {
        if (id > 0) {
            return Anima.select().from(Email.class).byId(id);
        }
        return null;
    }

    public Page<Email> page(int pageNo, int size, Integer status) {
        AnimaQuery<Email> from = Anima.select().from(Email.class)
                .order(Email::getStatus, OrderBy.ASC)
                .order(Email::getTime, OrderBy.DESC);
        if (status != null && status >= 0) {
            from.where(Email::getStatus, status);
        }
        Page<Email> page = from.page(pageNo, size);
        if (page != null && page.getTotalRows() > 0) {
            return page;
        }
        return null;
    }

    public Page<Email> like(String name) {
        Page<Email> page = Anima.select().from(Email.class)
                .like(Email::getName, name + "%")
                .page(1, Integer.MAX_VALUE);

        if (page != null && page.getTotalRows() > 0) {
            return page;
        }
        return null;
    }

    public long count(Integer status) {
        AnimaQuery<Email> from = Anima.select().from(Email.class);
        if (status != null && status >= 0) {
            from.where(Email::getStatus, status);
        }
        return from.count();
    }
}
